{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import time\n",
        "import json\n",
        "from typing import List, Dict, Any\n",
        "\n",
        "try:\n",
        "    import daytona_sdk\n",
        "except ImportError:\n",
        "    print(\"Installing Daytona SDK...\")\n",
        "    !pip install daytona-sdk\n",
        "    import daytona_sdk\n",
        "\n",
        "from daytona_sdk import Daytona, DaytonaConfig, CreateSandboxParams"
      ],
      "metadata": {
        "id": "SfWf-728jicc"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class DaytonaTutorial:\n",
        "    \"\"\"Complete tutorial for Daytona SDK - Secure AI Code Execution Platform\"\"\"\n",
        "\n",
        "    def __init__(self, api_key: str):\n",
        "        \"\"\"Initialize Daytona client\"\"\"\n",
        "        self.config = DaytonaConfig(api_key=api_key)\n",
        "        self.daytona = Daytona(self.config)\n",
        "        self.sandboxes: List[Any] = []\n",
        "\n",
        "    def basic_sandbox_demo(self):\n",
        "        \"\"\"Demo 1: Basic sandbox creation and code execution\"\"\"\n",
        "        print(\"🚀 Demo 1: Basic Sandbox Operations\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        try:\n",
        "            sandbox = self.daytona.create(CreateSandboxParams(language=\"python\"))\n",
        "            self.sandboxes.append(sandbox)\n",
        "\n",
        "            print(f\"✅ Created sandbox: {sandbox.id}\")\n",
        "\n",
        "            code = 'print(\"Hello from Daytona Sandbox!\")\\nprint(f\"2 + 2 = {2 + 2}\")'\n",
        "            response = sandbox.process.code_run(code)\n",
        "\n",
        "            if response.exit_code == 0:\n",
        "                print(f\"📝 Output: {response.result}\")\n",
        "            else:\n",
        "                print(f\"❌ Error: {response.result}\")\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"❌ Error in basic demo: {e}\")\n",
        "\n",
        "    def data_processing_demo(self):\n",
        "        \"\"\"Demo 2: Data processing in isolated environment\"\"\"\n",
        "        print(\"\\n📊 Demo 2: Secure Data Processing\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        try:\n",
        "            sandbox = self.daytona.create(CreateSandboxParams(language=\"python\"))\n",
        "            self.sandboxes.append(sandbox)\n",
        "\n",
        "            install_cmd = \"import subprocess; subprocess.run(['pip', 'install', 'pandas'])\"\n",
        "            response = sandbox.process.code_run(install_cmd)\n",
        "\n",
        "            data_code = \"\"\"\n",
        "import pandas as pd\n",
        "import json\n",
        "\n",
        "# Create sample dataset\n",
        "data = {\n",
        "    'name': ['Alice', 'Bob', 'Charlie', 'Diana'],\n",
        "    'age': [25, 30, 35, 28],\n",
        "    'salary': [50000, 60000, 70000, 55000]\n",
        "}\n",
        "\n",
        "df = pd.DataFrame(data)\n",
        "result = {\n",
        "    'total_records': len(df),\n",
        "    'avg_age': df['age'].mean(),\n",
        "    'avg_salary': df['salary'].mean(),\n",
        "    'summary': df.describe().to_dict()\n",
        "}\n",
        "\n",
        "print(json.dumps(result, indent=2))\n",
        "\"\"\"\n",
        "\n",
        "            response = sandbox.process.code_run(data_code)\n",
        "            if response.exit_code == 0:\n",
        "                print(\"✅ Data processing completed:\")\n",
        "                print(response.result)\n",
        "            else:\n",
        "                print(f\"❌ Error: {response.result}\")\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"❌ Error in data processing demo: {e}\")\n",
        "\n",
        "    def file_operations_demo(self):\n",
        "        \"\"\"Demo 3: File operations within sandbox\"\"\"\n",
        "        print(\"\\n📁 Demo 3: File Operations\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        try:\n",
        "            sandbox = self.daytona.create(CreateSandboxParams(language=\"python\"))\n",
        "            self.sandboxes.append(sandbox)\n",
        "\n",
        "            file_code = \"\"\"\n",
        "import os\n",
        "import json\n",
        "\n",
        "# Create a sample file\n",
        "data = {'message': 'Hello from Daytona!', 'timestamp': '2025-06-13'}\n",
        "with open('sample.json', 'w') as f:\n",
        "    json.dump(data, f, indent=2)\n",
        "\n",
        "# Read and display file contents\n",
        "with open('sample.json', 'r') as f:\n",
        "    content = f.read()\n",
        "    print(\"File contents:\")\n",
        "    print(content)\n",
        "\n",
        "# List files in current directory\n",
        "files = os.listdir('.')\n",
        "print(f\"\\\\nFiles in directory: {files}\")\n",
        "\"\"\"\n",
        "\n",
        "            response = sandbox.process.code_run(file_code)\n",
        "            if response.exit_code == 0:\n",
        "                print(\"✅ File operations completed:\")\n",
        "                print(response.result)\n",
        "            else:\n",
        "                print(f\"❌ Error: {response.result}\")\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"❌ Error in file operations demo: {e}\")\n",
        "\n",
        "    def ai_code_execution_demo(self):\n",
        "        \"\"\"Demo 4: Simulated AI-generated code execution\"\"\"\n",
        "        print(\"\\n🤖 Demo 4: AI-Generated Code Execution\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        ai_codes = [\n",
        "            \"# Calculate fibonacci sequence\\ndef fib(n):\\n    if n <= 1: return n\\n    return fib(n-1) + fib(n-2)\\nprint([fib(i) for i in range(10)])\",\n",
        "            \"# Sort algorithm\\ndef bubble_sort(arr):\\n    n = len(arr)\\n    for i in range(n):\\n        for j in range(0, n-i-1):\\n            if arr[j] > arr[j+1]:\\n                arr[j], arr[j+1] = arr[j+1], arr[j]\\n    return arr\\nprint(bubble_sort([64, 34, 25, 12, 22, 11, 90]))\",\n",
        "            \"# Data analysis\\nimport math\\ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\\nmean = sum(data) / len(data)\\nvariance = sum((x - mean) ** 2 for x in data) / len(data)\\nstd_dev = math.sqrt(variance)\\nprint(f'Mean: {mean}, Std Dev: {std_dev:.2f}')\"\n",
        "        ]\n",
        "\n",
        "        try:\n",
        "            sandbox = self.daytona.create(CreateSandboxParams(language=\"python\"))\n",
        "            self.sandboxes.append(sandbox)\n",
        "\n",
        "            for i, code in enumerate(ai_codes, 1):\n",
        "                print(f\"\\n🔄 Executing AI Code Snippet {i}:\")\n",
        "                response = sandbox.process.code_run(code)\n",
        "\n",
        "                if response.exit_code == 0:\n",
        "                    print(f\"✅ Output: {response.result}\")\n",
        "                else:\n",
        "                    print(f\"❌ Error: {response.result}\")\n",
        "\n",
        "                time.sleep(1)\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"❌ Error in AI code execution demo: {e}\")\n",
        "\n",
        "    def parallel_execution_demo(self):\n",
        "        \"\"\"Demo 5: Multiple sandboxes for parallel processing\"\"\"\n",
        "        print(\"\\n⚡ Demo 5: Parallel Execution\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        tasks = [\n",
        "            \"print('Task 1: Computing prime numbers')\\nprimes = [i for i in range(2, 50) if all(i % j != 0 for j in range(2, int(i**0.5) + 1))]\\nprint(f'Primes: {primes[:10]}')\",\n",
        "            \"print('Task 2: String processing')\\ntext = 'Hello Daytona World'\\nprint(f'Reversed: {text[::-1]}')\\nprint(f'Word count: {len(text.split())}')\",\n",
        "            \"print('Task 3: Mathematical calculations')\\nimport math\\nresult = sum(math.sqrt(i) for i in range(1, 101))\\nprint(f'Sum of square roots 1-100: {result:.2f}')\"\n",
        "        ]\n",
        "\n",
        "        try:\n",
        "            parallel_sandboxes = []\n",
        "            for i in range(len(tasks)):\n",
        "                sandbox = self.daytona.create(CreateSandboxParams(language=\"python\"))\n",
        "                parallel_sandboxes.append(sandbox)\n",
        "                self.sandboxes.append(sandbox)\n",
        "\n",
        "            results = []\n",
        "            for i, (sandbox, task) in enumerate(zip(parallel_sandboxes, tasks)):\n",
        "                print(f\"\\n🏃 Starting parallel task {i+1}\")\n",
        "                response = sandbox.process.code_run(task)\n",
        "                results.append((i+1, response))\n",
        "\n",
        "            for task_num, response in results:\n",
        "                if response.exit_code == 0:\n",
        "                    print(f\"✅ Task {task_num} completed: {response.result}\")\n",
        "                else:\n",
        "                    print(f\"❌ Task {task_num} failed: {response.result}\")\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"❌ Error in parallel execution demo: {e}\")\n",
        "\n",
        "    def cleanup_sandboxes(self):\n",
        "        \"\"\"Clean up all created sandboxes\"\"\"\n",
        "        print(\"\\n🧹 Cleaning up sandboxes...\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        for sandbox in self.sandboxes:\n",
        "            try:\n",
        "                self.daytona.remove(sandbox)\n",
        "                print(f\"✅ Removed sandbox: {sandbox.id}\")\n",
        "            except Exception as e:\n",
        "                print(f\"❌ Error removing sandbox {sandbox.id}: {e}\")\n",
        "\n",
        "        self.sandboxes.clear()\n",
        "        print(\"🎉 Cleanup completed!\")\n",
        "\n",
        "    def run_full_tutorial(self):\n",
        "        \"\"\"Run the complete Daytona tutorial\"\"\"\n",
        "        print(\"🎯 Daytona SDK Complete Tutorial\")\n",
        "        print(\"=\" * 50)\n",
        "        print(\"Secure & Isolated AI Code Execution Platform\")\n",
        "        print(\"=\" * 50)\n",
        "\n",
        "        self.basic_sandbox_demo()\n",
        "        self.data_processing_demo()\n",
        "        self.file_operations_demo()\n",
        "        self.ai_code_execution_demo()\n",
        "        self.parallel_execution_demo()\n",
        "        self.cleanup_sandboxes()\n",
        "\n",
        "        print(\"\\n🎊 Tutorial completed successfully!\")\n",
        "        print(\"Key Daytona features demonstrated:\")\n",
        "        print(\"• Secure sandbox creation\")\n",
        "        print(\"• Isolated code execution\")\n",
        "        print(\"• File system operations\")\n",
        "        print(\"• Parallel processing\")\n",
        "        print(\"• Resource cleanup\")"
      ],
      "metadata": {
        "id": "kGcaZWNbjphh"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def main():\n",
        "    \"\"\"Main function to run the tutorial\"\"\"\n",
        "\n",
        "    print(\"🔑 Daytona Setup Instructions:\")\n",
        "    print(\"1. Visit: https://app.daytona.io\")\n",
        "    print(\"2. Create an account\")\n",
        "    print(\"3. Generate API key at: https://app.daytona.io/dashboard/keys\")\n",
        "    print(\"4. Replace 'YOUR_API_KEY' below with your actual key\")\n",
        "    print(\"-\" * 50)\n",
        "\n",
        "    API_KEY = \"Use Your API Key Here\"\n",
        "\n",
        "    if API_KEY == \"YOUR_API_KEY\":\n",
        "        print(\"⚠️  Please set your Daytona API key before running the tutorial!\")\n",
        "        print(\"   Update the API_KEY variable with your key from https://app.daytona.io/dashboard/keys\")\n",
        "        return\n",
        "\n",
        "    try:\n",
        "        tutorial = DaytonaTutorial(API_KEY)\n",
        "        tutorial.run_full_tutorial()\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"❌ Tutorial failed: {e}\")\n",
        "        print(\"💡 Make sure your API key is valid and you have network access\")"
      ],
      "metadata": {
        "id": "IUjfEkFDjsKZ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KDBIFC1Khgfz",
        "outputId": "f1d91755-05ac-49fc-aa20-803245bfd6bf"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🔑 Daytona Setup Instructions:\n",
            "1. Visit: https://app.daytona.io\n",
            "2. Create an account\n",
            "3. Generate API key at: https://app.daytona.io/dashboard/keys\n",
            "4. Replace 'YOUR_API_KEY' below with your actual key\n",
            "--------------------------------------------------\n",
            "🎯 Daytona SDK Complete Tutorial\n",
            "==================================================\n",
            "Secure & Isolated AI Code Execution Platform\n",
            "==================================================\n",
            "🚀 Demo 1: Basic Sandbox Operations\n",
            "----------------------------------------\n",
            "✅ Created sandbox: 96644a52-e6c0-4d63-a0e1-d605df0f15e8\n",
            "📝 Output: Hello from Daytona Sandbox!\n",
            "2 + 2 = 4\n",
            "\n",
            "\n",
            "📊 Demo 2: Secure Data Processing\n",
            "----------------------------------------\n",
            "✅ Data processing completed:\n",
            "{\n",
            "  \"total_records\": 4,\n",
            "  \"avg_age\": 29.5,\n",
            "  \"avg_salary\": 58750.0,\n",
            "  \"summary\": {\n",
            "    \"age\": {\n",
            "      \"count\": 4.0,\n",
            "      \"mean\": 29.5,\n",
            "      \"std\": 4.203173404306164,\n",
            "      \"min\": 25.0,\n",
            "      \"25%\": 27.25,\n",
            "      \"50%\": 29.0,\n",
            "      \"75%\": 31.25,\n",
            "      \"max\": 35.0\n",
            "    },\n",
            "    \"salary\": {\n",
            "      \"count\": 4.0,\n",
            "      \"mean\": 58750.0,\n",
            "      \"std\": 8539.125638299665,\n",
            "      \"min\": 50000.0,\n",
            "      \"25%\": 53750.0,\n",
            "      \"50%\": 57500.0,\n",
            "      \"75%\": 62500.0,\n",
            "      \"max\": 70000.0\n",
            "    }\n",
            "  }\n",
            "}\n",
            "\n",
            "\n",
            "📁 Demo 3: File Operations\n",
            "----------------------------------------\n",
            "✅ File operations completed:\n",
            "File contents:\n",
            "{\n",
            "  \"message\": \"Hello from Daytona!\",\n",
            "  \"timestamp\": \"2025-06-13\"\n",
            "}\n",
            "\n",
            "Files in directory: ['.bash_logout', '.bashrc', '.profile', '.daytona', 'sample.json']\n",
            "\n",
            "\n",
            "🤖 Demo 4: AI-Generated Code Execution\n",
            "----------------------------------------\n",
            "\n",
            "🔄 Executing AI Code Snippet 1:\n",
            "✅ Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n",
            "\n",
            "\n",
            "🔄 Executing AI Code Snippet 2:\n",
            "✅ Output: [11, 12, 22, 25, 34, 64, 90]\n",
            "\n",
            "\n",
            "🔄 Executing AI Code Snippet 3:\n",
            "✅ Output: Mean: 5.5, Std Dev: 2.87\n",
            "\n",
            "\n",
            "⚡ Demo 5: Parallel Execution\n",
            "----------------------------------------\n",
            "\n",
            "🏃 Starting parallel task 1\n",
            "\n",
            "🏃 Starting parallel task 2\n",
            "\n",
            "🏃 Starting parallel task 3\n",
            "✅ Task 1 completed: Task 1: Computing prime numbers\n",
            "Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n",
            "\n",
            "✅ Task 2 completed: Task 2: String processing\n",
            "Reversed: dlroW anotyaD olleH\n",
            "Word count: 3\n",
            "\n",
            "✅ Task 3 completed: Task 3: Mathematical calculations\n",
            "Sum of square roots 1-100: 671.46\n",
            "\n",
            "\n",
            "🧹 Cleaning up sandboxes...\n",
            "----------------------------------------\n",
            "✅ Removed sandbox: 96644a52-e6c0-4d63-a0e1-d605df0f15e8\n",
            "✅ Removed sandbox: fe7093a9-dd31-4b71-9f4b-fa9f3cd57329\n",
            "✅ Removed sandbox: cd54cb87-3775-47a6-ab06-fba013b4f2a4\n",
            "✅ Removed sandbox: 85d5a166-5457-43e9-b8d8-15bb6e137445\n",
            "✅ Removed sandbox: 79033eb0-bcc5-4db9-8cb4-225601908c41\n",
            "✅ Removed sandbox: 1c7ffff5-4eba-4aa0-a8ef-f3c768c71a4f\n",
            "✅ Removed sandbox: fe867978-a458-43ab-8177-08f31b39f9a2\n",
            "🎉 Cleanup completed!\n",
            "\n",
            "🎊 Tutorial completed successfully!\n",
            "Key Daytona features demonstrated:\n",
            "• Secure sandbox creation\n",
            "• Isolated code execution\n",
            "• File system operations\n",
            "• Parallel processing\n",
            "• Resource cleanup\n"
          ]
        }
      ],
      "source": [
        "if __name__ == \"__main__\":\n",
        "    main()"
      ]
    }
  ]
}